// Camera.cpp
//
// Class for controlling a camera.
//
// Author: Nick Kitten
// 2009

#include "Camera.h"
#include <cassert>

Camera::Camera( int id, float x, float y, float z, float rx, float ry, float rz )
: PoseableObject( id, x, y, z, rx, ry, rz )
{
	dbMakeCamera( id );
}

Camera::~Camera()
{
	dbDeleteCamera( getID() );
}

void Camera::setPosition(float x, float y, float z)
{
	Object::setPosition( x, y, z );
	//int lastActiveCam = activeID;
	//makeActive();
	dbPositionCamera( getID(), x, y, z );
	///dbSetCurrentCamera( lastActiveCam );
	dbMakeObjectCone( 9500, 20 );
	//dbXRotateObject( 9500, 90 );
	//dbFixObjectPivot( 9500 );
	dbPositionObject( 9500, getPosX(), getPosY(), getPosZ() );
	dbRotateObject( 9500, 90, getRotY(), getRotZ() );
	dbColorObject( 9500, dbRGB(0, 0, 255) );
}

void Camera::setRotation(float x, float y, float z)
{
	PoseableObject::setRotation( x, y, z );

	//int lastActiveCam = activeID;
	//makeActive();
	dbRotateCamera( getID(), x, y, z );
	//dbSetCurrentCamera( lastActiveCam );
}

void Camera::makeActive()
{
	dbSetCurrentCamera( getID() );
	activeID = getID();
}

bool Camera::isActive() const
{
	return getID() == activeID;
}

void Camera::setView( int width, int height, int x, int y )
{
	makeActive();
	viewArea.minPoint = Position( x, y );
	viewArea.maxPoint = Position( x + width, y + height );
	dbSetCameraView( x, y, viewArea.maxPoint.x, viewArea.maxPoint.y );
}
	
Rect Camera::getView() const
{
	return viewArea;
}

void Camera::lookAt( float x, float y, float z )
{
	int lastActiveCam = activeID;
	makeActive();
	dbPointCamera( getID(), x, y, z );
	setRotation( dbCameraAngleX( getID() ), dbCameraAngleY( getID() ), dbCameraAngleZ( getID() ) );
	dbSetCurrentCamera( lastActiveCam );
}

void Camera::setToImage( int ID, int width, int height )
{
	assert( ID != 0 );
	dbSetCameraToImage( getID(), ID, width, height );
	imageID = ID;
}

void Camera::display()
{
	// Print to screen in small viewport
	int width = viewArea.maxPoint.x - viewArea.minPoint.x;
	int height = viewArea.maxPoint.y - viewArea.minPoint.y;
	
	setToImage( imageID, width, height );
	assert( dbImageExist( imageID ) );
	dbPasteImage( imageID, viewArea.minPoint.x, viewArea.minPoint.y );
}

void Camera::displayMain()
{
	// Save view area
	Rect smallView = viewArea;

	int width = viewArea.maxPoint.x - viewArea.minPoint.x;
	int height = viewArea.maxPoint.y - viewArea.minPoint.y;

	// Print to fill screen
	setView( dbScreenWidth(), dbScreenHeight() );
	setToImage( imageID, width, height );
	dbPasteImage( imageID, viewArea.minPoint.x, viewArea.minPoint.y );
	assert( dbImageExist( imageID ) );

	// Restore small view
	width = smallView.maxPoint.x - smallView.minPoint.x;
	height = smallView.maxPoint.y - smallView.minPoint.y;
	setView( width, height, smallView.minPoint.x, smallView.minPoint.y );
}

int Camera::activeID = 1;